package cn.com.customer.manager.manager

import android.content.Context
import android.content.SharedPreferences
import cn.com.customer.manager.Constants
import cn.com.customer.manager.bean.User
import com.google.gson.Gson
import com.xuexiang.xutil.net.JsonUtil

/**
 */
class LoginManager private constructor(context: Context) {

    companion object {
        @Volatile
        private var instance: LoginManager? = null

        fun getInstance(context: Context): LoginManager {
            if (instance == null) {
                synchronized(LoginManager::class.java) {
                    if (instance == null) {
                        instance = LoginManager(context.applicationContext)
                    }
                }
            }
            return instance!!
        }
    }

    private var mUser: User? = null

    private var isLogin: Boolean = false

    val mPreferences: SharedPreferences = context.getSharedPreferences(Constants.USER, Context.MODE_PRIVATE)

    /**
     * 获取用户信息
     */
    val user: User?
        get() = getCurrentUser(User::class.java)

    /**
     * 获取用户信息
     */
    private fun getCurrentUser(class1: Class<User>): User? {
        mUser = JsonUtil.fromJson(mPreferences.getString(Constants.USER, ""), class1)
        return mUser
    }

     fun saveUser(user: User) {
        mPreferences.edit().putString(Constants.USER, Gson().toJson(user)).commit()
    }

    /**
     * 清除登录信息
     */
    fun clearLoginState() {
        mPreferences.edit().clear().commit()
        mUser = null
        isLogin = false
    }
}